const express = require("express")
const router = express.Router()
const multer = require("multer")
const path = require("path")
const articleTable = require("../../database/article")


router.post("/uploadMd", (req, res) => {
    let name = null;
    //配置multer
    let upload = multer({

        storage: multer.diskStorage({
            destination: function (req, file, callback) {
                callback(null, path.join(__dirname, "../../public/file/article"))
            },
            // 设置文件的名字 （防重名）
            filename: function (req, file, callback) {
                let { ext } = path.parse(file.originalname)
                name = 'md-' + new Date().getTime() + ext
                callback(null, name)
            }
        })
    }).single("file")
    upload(req, res, async (err) => {
        //上传失败
        if (err) {
            res.send({ code: 9, message: "上传失败" });
        } else {
            res.send({ code: 0, message: "md文件上传成功", mdUrl: `/file/article/${name}` });
        }
    });
})



router.post("/uploadCover", (req, res) => {
    let name = null;
    // 配置multer中间件处理上传的图片文件
    let upload = multer({
        // 配置项
        storage: multer.diskStorage({
            // 设置文件存储在服务端的那个目录
            destination: function (req, file, callback) {
                callback(null, path.join(__dirname, "../../public/file/cover"))
            },
            // 设置文件的名字 （防重名）
            filename: function (req, file, callback) {
                let { ext } = path.parse(file.originalname);
                name = 'cover-' + new Date().getTime() + ext;
                callback(null, name);
            }
        })

    }).single("file");

    upload(req, res, async (err) => {
        if (err) {
            res.send({
                code: 4,
                message: "封面上传失败"
            })
        } else {
            res.send({
                code: 0,
                message: "封面上传成功",
                coverUrl: `/file/cover/${name}`
            })
        }
    })

})

//监听文章数据的路由，将文章数据添加到数据库中
router.post("/add", async (req, res) => {
    let { title, desc, mdUrl, coverUrl } = req.body;
    //将文章数据存到数据表
    let doc = await articleTable.create({
        title: title || undefined,
        desc: desc || undefined,
        mdUrl,
        coverUrl: coverUrl || undefined,
        author: req.session.userInfo._id
    });
    res.send({ code: 0, message: "文章发表成功", data: { id: doc._id } });  //返回文章id
})

module.exports = router